"""Group views."""

from django import forms
from django.conf import settings
from hcp.auth.decorators import permission_required
from hcp.forms.choice import ChoiceWithOtherField
from hcp.forms.custom import MyDynamicField, MyGroupedForm
from hcp.forms.grouped import FormSection
from hcp.forms.util import form_from_model
from hcp.jinja import render_to_response
from hcp.ldap_models import Group, update_model_from_post, set_auto_manual_id
from hcp.tracking import HcpCallback
from hcp.util.json import JsonResponse

gidNumber_choices = (('AUTO', 'Create new GID.'), ('MANUAL', 'Manually enter GID:'))

def create_group_form(new_group):

    class GroupForm(MyGroupedForm):

        def __init__(self, *args, **kwargs):
            kwargs['filter_fields'] = settings.GROUP_FIELDS_EXCLUDE
            super(GroupForm, self).__init__(*args, **kwargs)

        class Required(FormSection):

            label = 'Required Attributes'

            cn = MyDynamicField(forms.CharField(), label='Name')
            gidNumber = [forms.IntegerField(min_value=0, label='GID Number'),
                         ChoiceWithOtherField(choices=gidNumber_choices,
                            initial=('AUTO', ''),
                            other_field=forms.IntegerField(min_value=0),
                            label='GID Number'),
                        ][int(new_group)]

        class Members(FormSection):

            label = 'Members'

            memberUid = MyDynamicField(forms.CharField(),
                                       label='Member Username',
                                       required=False)

        class OtherAttributes(FormSection):

            label = 'Other Attributes'

            description = MyDynamicField(forms.CharField(),
                                         label='Description',
                                         required=False)
            userPassword = MyDynamicField(forms.CharField(widget=forms.widgets.PasswordInput),
                                          label='Password',
                                          required=False)

    return GroupForm

@permission_required('manage_groups')
def group_list(request):
    groups = Group.objects.all()

    data = [ {'cn':group.cn[0],
              'dn':group.dn,
              'gidNumber':group.gidNumber} for group in groups ]

    return JsonResponse({
        'groups': data,
    })

@permission_required('manage_groups')
def index(request):
    return render_to_response('groups/index.html', request=request)

@permission_required('manage_groups')
def new(request):
    GroupForm = create_group_form(new_group=True)
    if request.method == 'POST':
        form = GroupForm(request.POST, request.FILES)

        if form.is_valid():
            group = Group()
            fields = form.fields.keys()
            fields.remove('gidNumber')
            update_model_from_post(group, form.cleaned_data, fields)

            set_auto_manual_id('gidNumber', form, group, Group, settings.POSIX_MIN_GID)

            group.save(callback=HcpCallback(request.user.uid[0]))
            # XXX: Handle errors.
            # XXX: Make this a dialog instead of a separate page.
            return render_to_response('groups/group_created.html', {'group': group}, request=request)
    else:
        form = GroupForm()

#         'GROUP_FIELDS_EXCLUDE': settings.GROUP_FIELDS_EXCLUDE,

    return render_to_response('groups/new.html',
        {'form': form,
        }, request=request)

@permission_required('manage_groups')
def edit(request, dn):
    GroupForm = create_group_form(new_group=False)
    group = Group.objects.get_dn(dn)
    # XXX not found

    if request.method == 'POST':
        form = GroupForm(request.POST, request.FILES)
        if form.is_valid():
            update_model_from_post(group, form.cleaned_data, form.fields.keys())
            group.save(callback=HcpCallback(request.user.uid[0]))
            # XXX: Handle errors.

            return render_to_response('groups/group_edited.html', {'group': group}, request=request)
    else:
        form = form_from_model(GroupForm, group)

    return render_to_response('groups/edit.html',
        {'group': group,
         'form': form,
        },
        request=request)

@permission_required('manage_groups')
def remove(request, dn):
    group = Group.objects.get_dn(dn)
    group.delete(callback=HcpCallback(request.user.uid[0]))
    return JsonResponse({
        'result': 'success',
    })
